// pages/search/search.js

const app = getApp()
const API = require('../../utils/api')
const plugin = requirePlugin("WechatSI")

// 获取**全局唯一**的语音识别管理器**recordRecoManager**
const manager = plugin.getRecordRecognitionManager()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchNameValue: "",
    isActive:false,
    searchData:[
      {
        id:1,
        cover:"/image/mine/avatar.png",
        description:"如何在手机上挂号问诊",
        learned:34
      },
      {
        id:2,
        cover:"/image/mine/avatar.png",
        description:"如何在手机上挂号问诊",
        learned:34
      },
      {
        id:3,
        cover:"/image/mine/avatar.png",
        description:"如何在手机上挂号问诊",
        learned:34
      },
      {
        id:4,
        cover:"/image/mine/avatar.png",
        description:"如何在手机上挂号问诊",
        learned:34
      },
      {
        id:5,
        cover:"/image/mine/avatar.png",
        description:"如何在手机上挂号问诊",
        learned:3
      }
    ],
    customizedSearchImage: "",
    showSpeechPopup: false,
    holdSpeechimage: "/image/search/6-speech.png",
    recording:false,
    searchHistory:[],
    showSearchResult: false,
    searchResult:[],
    hotSearch:[]
  },

  onClearHistory(){
    this.setData({
      searchHistory:[]
    })
  },

  /**
   * 按住按钮开始语音识别
   */
  streamRecord: function(e) {
    // console.log("streamrecord" ,e)
    // 先清空背景音
    // wx.stopBackgroundAudio()

    manager.start({
      lang: "zh_CN",
    })

    this.setData({
      recording: true,
      searchNameValue: "",
      // holdSpeechimage: "/image/search/7-speechActive.png",
      isActive: true,
    })

  },

  /**
   * 松开按钮结束语音识别
   */
  streamRecordEnd: function(e) {

    // console.log("streamRecordEnd" ,e)

    manager.stop()

    this.setData({
      bottomButtonDisabled: true,
      recording:false,
      // holdSpeechimage: "/image/search/6-speech.png",
      isActive: false,
    })
  },

    /**
   * 初始化语音识别回调
   * 绑定语音播放开始事件
   */
  initRecord: function() {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      let text = res.result
      console.log("有新的结果返回")
      this.setData({
        searchNameValue: text,
        showSpeechPopup: false,
      })
      
    }

    // 识别结束事件
    manager.onStop = (res) => {

      let text = res.result

      if(text == '') {
        return
      }

      this.setData({
        searchNameValue: text,
        showSpeechPopup: false,
      })
      this.searchMine(text)
    }

    // 识别错误事件
    manager.onError = (res) => {
      console.log("识别出错！")

      // this.setData({
      //   recording: false,
      //   bottomButtonDisabled: false,
      // })

    }
  },
  // 点击搜索的课程
  tapToCourse(event){
    console.log("点击的课程id是：", event.currentTarget.dataset)
    if(wx.getStorageSync('accessTokenData').accessToken){
      wx.navigateTo({
        url: `/pages/courseDetail/index?id=${event.currentTarget.dataset.id}`,
      })
    }
    else{
        wx.showToast({
          title: '请前往“我的”授权登录！',
          icon: "none",
          duration: 2000
        })
    } 
  },

  tapSpeechTab1() {
    app.getRecordAuth()
    this.setData({ showSpeechPopup: true })    
  },
  
  tapSpeechTab2() {
    app.getRecordAuth()
    this.setData({ showSpeechPopup: true })
  },

  onClose() {
    this.setData({ showSpeechPopup: false });
  },

  tapSearchHistory(event){
    console.log("点击搜索历史：",event.currentTarget)
    this.searchMine(event.currentTarget.dataset.value)
  },
  tapHotSearch(event){
    console.log("点击热门搜索：",event.currentTarget)
    this.setData({
      searchNameValue: event.currentTarget.dataset.value
    })
    this.searchMine(event.currentTarget.dataset.value)
  },

  tapSearch(){
    console.log("点击搜索！",this.data.searchNameValue)
    this.searchMine(this.data.searchNameValue)
  },

  onConfirm(e){
    console.log("点击搜索框确定！",e.detail)
    this.searchMine(e.detail)
  },

  onChange(e){
    // console.log("搜索框改变！",e.detail)
    console.log("搜索框改变！")
  },
  onClearInput(e){
    console.log("搜索框清除！",e.detail)
    this.setData({
      searchResult:[],
      showSearchResult: false
    })
  },
  onClearSearch(e){
    console.log("搜索清除！",e.detail)
    this.setData({
      searchResult:[],
      showSearchResult: false,
      searchNameValue: ""
    })
  },

  searchMine(value){
    if(value.endsWith("?")||value.endsWith("!")||value.endsWith("？")||value.endsWith("！")||value.endsWith(".")||value.endsWith("。")||value.endsWith("，")||value.endsWith(","))
    {
      value=value.slice(0,value.length-1)
      this.setData({
        searchNameValue: value
      })
    }
    if(value.length>0){
      let searchHistoryNew=this.data.searchHistory
      if(!searchHistoryNew.includes(value)){
        if(searchHistoryNew.length>10){
          searchHistoryNew.shift()
        }
        searchHistoryNew.unshift(value)
      }
      
      // wx.
      // this.setData({
      //   searchHistory: searchHistoryNew,
      //   searchResult:[{
      //     id:0,
      //     cover:'/image/1-home-1.png',
      //     description:'如何在手机上挂号问诊',
      //     learned: 23
      //   }],
      //   showSearchResult: true
      // })
      wx.request({
        url: API.COURSEList,
        header:{
          "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken
        },
        method: "get",
        data: { search: value },
        success: (res) => {
          console.log("搜索课程成功：",res)
          if(res.data.data.length===0){
            wx.showToast({
              title: '暂无搜索课程',
              icon:'error'
            })
          }
          this.setData({
            searchHistory: searchHistoryNew,
            searchResult: res.data.data,
            showSearchResult: true
          })     
        },
        fail: (err) => {
          console.log("获取课程列表出错：",err);
        },
        complete:()=>{
        }
      })
    }
    else{
      wx.showToast({
        title: '请输入名称',
        icon:'error'
      })
    }
  },


  loadHotSearch(){
    wx.request({
      url: API.HotSearch,
      header:{
        "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken
      },
      method: "get",
      success: (res) => {
        console.log("热门搜索关键词获取成功：",res)
        this.setData({
          hotSearch: res.data.data
        })
      },
      fail: (err) => {
        console.log("获取热门搜索关键词出错：",err)
      },
      complete:()=>{
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let searchHistoryInit = wx.getStorageSync('searchHistory')
    if(searchHistoryInit){
      this.setData({
        searchHistory: searchHistoryInit
      })
    }
    
    // this.getHistory()
    this.initRecord()
    this.loadHotSearch()
    // this.setData({toView: this.data.toView})
    // app.getRecordAuth()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("退出")
    wx.setStorageSync('searchHistory', this.data.searchHistory)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})